/**
 * @file rising_dege.c
 * @author your name (you@domain.com)
 * @brief
 * @version 0.1
 * @date 2025-04-09
 *
 * @copyright Copyright (c) 2025
 *
 */
#include "rising_dege.h"

void init_rising_detector(RisingEdgeDetector *detector,
                          RisingEdgeMonitor *buffer, size_t capacity) {
  detector->monitors = buffer;
  detector->count = 0;
  detector->capacity = capacity;
}
int bind_rising_variable(RisingEdgeDetector *detector, uint8_t *variable) {
  if (detector->count >= detector->capacity) {
    return -1; // 容量不足，绑定失败
  }

  RisingEdgeMonitor *monitor = &detector->monitors[detector->count];
  monitor->variable = variable;
  monitor->last_state = *variable; // 初始化为当前值
  monitor->rising_trigger = 0;     // 初始化触发标志
  detector->count++;

  return 0; // 绑定成功
}
void detect_rising_edges(RisingEdgeDetector *detector) {
  for (size_t i = 0; i < detector->count; i++) {
    RisingEdgeMonitor *monitor = &detector->monitors[i];
    uint8_t current_state = *(monitor->variable);

    // 检测上升沿并更新触发标志
    if (monitor->last_state == 0 && current_state == 1) {
      monitor->rising_trigger = 1;
    } else {
      monitor->rising_trigger = 0; // 仅在触发时为1，其他情况清零
    }

    // 更新状态
    monitor->last_state = current_state;
  }
}
uint8_t is_rising_edge_triggered(RisingEdgeDetector *detector,
                                 uint8_t *variable) {
  for (size_t i = 0; i < detector->count; i++) {
    if (detector->monitors[i].variable == variable) {
      return detector->monitors[i].rising_trigger;
    }
  }
  return 0; // 未找到该变量，返回未触发
}
